
import { TimeObserver } from "./TimeObserver";


/**
 * 时间的更新方式
 * 0 递减 
 * 1 递增 
 */
// export enum TimeUpdateType {
//     SUB,//倒计时
//     ADD,//距离活动时间
//     UPDATE,//定时触发
//     FRAME//每帧直接调用
// }

export class TimeManager  {

    static instance<T extends {}>(this: new () => T): T {
        if (!(<any>this).ins) {
            (<any>this).ins = new this();
        }
        return (<any>this).ins;
    }
    //时间计数
    private totalTime: number = 0;

    private observerList: Array<TimeObserver> = [];

    protected removes: TimeObserver[] = []


    protected running: boolean = true;
    protected time: number = 0;
    pause() {
        this.running = false;
        this.time = Date.now();
    }

    resume() {
        this.running = true;
        this.time = Date.now() - this.time;
    }

    reset() {
        this.totalTime = 0;
    }


    add(observer: TimeObserver) {
        let index = this.has(observer)
        if (index >= 0) {
            return;
        }
        this.observerList.push(observer);
    }

    has(observer: TimeObserver) {
        let index = this.observerList.indexOf(observer)
        return index

    }

    remove(observer: TimeObserver) {
        let index = this.has(observer)
        if (index >= 0) {
            this.observerList.splice(index, 1);
        }

    }

    getTotalTime() {
        return this.totalTime;
    }

    update(dt: number) {
        if (!this.running) {
            return;
        }
        if (this.time > 0) {
            console.log(' this time == ', this.time)
            dt += this.time / 1000;
            this.time = 0;
        }
        this.totalTime += dt
        this.removes.length = 0;
        for (let index = 0; index < this.observerList.length; index++) {
            const element: TimeObserver = this.observerList[index];
            if (element.update(dt)) {
                if (element.isAutoDelete()) {
                    this.removes.push(element)
                }
            }
        }
        while (this.removes.length > 0) {
            this.remove(this.removes.shift())
        }
    }

}





